package com.sinheldrin.musicplayer.player
{
	import flash.events.Event;
	
	import mx.controls.SWFLoader;

	public class YoutubePlayerController
	{
		private static const YOUTUBE_API_URL:String = "http://www.youtube.com/apiplayer?version=3";
		
		private static const STATE_ENDED:Number = 0;
		private static const STATE_PLAYING:Number = 1;
		private static const STATE_PAUSED:Number = 2;
		private static const STATE_CUED:Number = 5;
		
		public function YoutubePlayerController(masterPlayer:PlayerController)
		{
			_masterPlayer = masterPlayer;
		}
		
		public function init():void
		{	
			_playerLoader = new SWFLoader ();
			_playerLoader.addEventListener (Event.INIT, onLoaderInit);
			_playerLoader.load (YOUTUBE_API_URL);
		}
		
		private var _masterPlayer:PlayerController = null;
		
		private var _playerLoader:SWFLoader;
		private var _player:YoutubePlayerWrapper;
		
		private function onLoaderInit (event:Event):void
		{
			_masterPlayer.view.youtubePlayerContainer.addElement(_playerLoader);
			_player = new YoutubePlayerWrapper(_playerLoader.content);
			_player.addEventListener("onReady", onPlayerReady);
			_player.addEventListener("onError", onPlayerError);
			_player.addEventListener("onStateChange", onPlayerStateChange);
		}
		
		private function onPlayerReady(event:Event):void
		{
			// !!!!!!!!! CHECK IF YOUTUBE PLAYER HANDLE EVENT METHODS OTHER THAN ADDEVENTLISTENER !!!!!!!!!!!
			_player.removeEventListener("onReady", onPlayerReady);
			_player.setSize(200, 200);
			setVolume(_masterPlayer.model.volume);
			_masterPlayer.model.addEventListener(PlayerModel.VOLUME_CHANGE, onVolumeChange);
		}
		
		private function onPlayerError(event:Event):void
		{
			trace("Player error:", Object(event).data);
		}
		
		private function onPlayerStateChange(event:Event):void
		{
			var state:Number = Object(event).data;
			trace("State is", state);
			
			switch (state)
			{
				case STATE_ENDED:
					_masterPlayer.autoPlay();
					break;
			}
		}
		
		public function cue(videoId:String):void
		{
			_player.cueVideoById (videoId);
		}
		
		public function play():void
		{
			_player.playVideo();
		}
		
		public function pause():void
		{
			_player.pauseVideo();
		}
		
		public function stop():void
		{
			_player.pauseVideo();
			_player.seekTo(0, false);
		}
		
		private function onVolumeChange(event:Event):void
		{
			setVolume(_masterPlayer.model.volume);
		}
		
		public function setVolume(value:Number):void
		{
			_player.setVolume(value);
		}
		
		public function getCurrentTime():Number
		{
			return _player.getCurrentTime();
		}
		
		public function getDuraction():Number
		{
			return _player.getDuration();
		}
	}
}